package leetcode.D100.T21;

import util.ListNode;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: DYZ
 * @Create: 2021-08-09 15:27:05 星期一
 */

public class Solution {
    // 一刷
    /*public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }
        ListNode head = new ListNode(), a, b;
        if(l1.val <= l2.val) {
            head.next = l1;
            a = l1.next;
            b = l2;
        } else {
            head.next = l2;
            a = l1;
            b = l2.next;
        }
        ListNode tail = head.next;
        while(a != null && b != null) {
            if(a.val <= b.val) {
                tail.next = a;
                a = a.next;
            } else {
                tail.next = b;
                b = b.next;
            }
            tail = tail.next;
        }
        tail.next = a == null ? b : a;
        return head.next;
    }*/

    // 二刷
    /*public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(), p = head;
        while(l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                p.next = l1;
                l1 = l1.next;
            } else {
                p.next = l2;
                l2 = l2.next;
            }
            p = p.next;
        }
        p.next = l1 == null ? l2 : l1;
        return head.next;
    }*/

    // 三刷
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(), p = head;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                p.next = l1;
                l1 = l1.next;
            } else {
                p.next = l2;
                l2 = l2.next;
            }
            p = p.next;
        }
        p.next = l1 == null ? l2 : l1;
        return head.next;
    }
}
